//
//  BaseUserModel.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/12.
//

import UIKit

// 用户模型 一般来说包含登陆功能的App都会有用户模型存在
@objcMembers

class BaseUserModel: BaseModel, NSSecureCoding {
    // 用户模型属性
    var id : Int = 0

    var nickName : String = ""
    var headerImg : String = ""
    var sex : Int = 0
    var phone : String = ""
    
    var access_token : String = ""
    var channelToken : String = ""
    
    var completeInformation : Bool = false
    var isAccomplishEducation : Bool = false
    var isAccomplishLoanInfo : Bool = false
    var isAccomplishRelationship : Bool = false
    var isAccomplishWorkInfo : Bool = false
    var isFace : Bool = false
    
    required init() {
        super.init()
    }

    init(dict: [String: Any]) {
        super.init()
        setValuesForKeys(dict)
    }

    required init?(coder aDecoder: NSCoder) {
        //先初始化
        super.init()
        //获取当前类的所有属性名
        let nameList = getPropertyNameList
        //进行解档
        for key in nameList {
            //从aDecoder中取值
            let value = aDecoder.decodeObject(forKey: key)
            //赋值给自己
            if value != nil {
                setValue(value, forKey: key)
            }
        }
    }

    static var supportsSecureCoding: Bool { return true }

    // 获取id便捷方法
    static var id : Int = {
        BaseUserModel.unarchiver()?.id ?? 0
    }()!

    func encode(with aCoder: NSCoder) {
        //获取当前类的所有属性名
        let nameList = getPropertyNameList
        //进行归档
        for key in nameList{
            //KVC取值
            if let value = value(forKey: key){
                //归档.此处注意归档的方法中要使用带 forKey参数的
                aCoder.encode(value, forKey: key)
            }
        }
    }

    // 用户模型快速归档
    func archiver() {
        let result : Bool = ArchiverManager.shared.setData(data: self, forKey: "userModel", path: BaseUserModel.savePath())
        print("归档 \(result)")
    }

    // 用户模型快速读档
    static func unarchiver() -> BaseUserModel? {
        ArchiverManager.shared.getData(forKey: "userModel", forPath: savePath()) as? BaseUserModel
    }

    // 退出登录
    class func logout() {
        if BaseUserModel.unarchiver() != nil {
            ArchiverManager.shared.removeData(forPath: savePath())
        }
    }

    // 归档路径
    class func savePath() -> String {
        let fileName = NSStringFromClass(self) as String
        return "/" + fileName + ".plist"
    }

    // 登录检查
    class func checkUser(needPushLogin : Bool, withoutTip : Bool = false) -> Bool {
        if BaseUserModel.unarchiver() != nil {
            return true
        }

        if needPushLogin {
            let nav = QMUINavigationController(rootViewController: LoginViewController())
            nav.modalPresentationStyle = .fullScreen
            AppDelegate.appDelegate.window?.rootViewController?.present(nav, animated: true, completion: {
                if !withoutTip {
                    QMUITips.showInfo("请先登录")
                }
            })
        }
        return false
    }
    
    class func refreshUserInfo(completeBlock : (()->Void)? = nil) {
        if let model = BaseUserModel.unarchiver() {
            NetworkManager.manager.request(targetType: .initUserInfo, responseModelType: NetworkBaseModel<BaseUserModel>.self) { responseModel in
                if responseModel.code == .invalidToken {
                    let nav = QMUINavigationController(rootViewController: LoginViewController())
                    AppDelegate.appDelegate.window?.rootViewController = nav
                    QMUITips.showInfo("登录失效，请重新登录")
                    return
                }
                if responseModel.code == .successCode {
                    let configModel = YHBaseConfiguration.shared.configModel ?? WMConfigModel()
                    let newModel = responseModel.data!
                    newModel.phone = model.phone
                    newModel.access_token = model.access_token
                    newModel.channelToken = model.channelToken
                    newModel.archiver()
                    
                    if (configModel.face == false || newModel.isFace == true)
                        && (configModel.relationship == false || newModel.isAccomplishRelationship)
                        && (configModel.education == false || newModel.isAccomplishEducation)
                        && (configModel.workInformation == false || newModel.isAccomplishWorkInfo)
                        && (configModel.loanAssistance == false || newModel.completeInformation)
                        && (configModel.loanInformation == false || newModel.isAccomplishLoanInfo) {
                        CustomRelay.manager.tabbarStatusBehaviorRelay.accept(false)
                    } else {
                        CustomRelay.manager.tabbarStatusBehaviorRelay.accept(true)
                    }
                    completeBlock?()
                }
            }
        }
    }
}
